#!/usr/bin/perl

# File: backup.pl
# Author: Arvind Subramanian (somdev3)
# Language: Perl 5

use strict;
use DBI;
use Getopt::Long;
use Backup::Create;

# Mysql Username Config
my $dbiUsername = "";
my $dbiPassword = "";
my $dbiHost = "";
my $dbiSocket = "";

# Backup information
my $backupFolder = "";

# Get command line input
my $customName;my $force = 0;
GetOptions('o:s'=>\$customName,
	'u:s'=>\$dbiUsername,
	'p:s'=>\$dbiPassword,
	'h:s'=>\$dbiHost,
	's:s'=>\$dbiSocket,
	'd:s'=>\$backupFolder,
	'f'=>\$force);


#Get Local time
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);$year += 1900;$mon++;$mon = $mon > 9 ? "$mon" : "0".$mon;$mday = $mday > 9 ? "$mday" : "0".$mday;

#Make sure directory format is consistent
$backupFolder = dirFormat($backupFolder);
#Connect to database, get list of databases
my $dbh = DBI->connect("DBI:mysql:information_schema;host=$dbiHost;socket=$dbiSocket;",$dbiUsername,$dbiPassword);
my $databases = $dbh->selectcol_arrayref("SHOW DATABASES;");

#my @databases = @$databases;
my @databases = ("mwiki","StudTest","som_it");
#Make directory to package up later $backupFolder/%Y%M%D/
my $dirname;
if ( $customName ) {
	$dirname = "$backupFolder/$customName";
} else {
	$dirname = "$backupFolder/$year$mon$mday";
}
mkdir($dirname);

if ( -f "$dirname/backup.ini" && !$force ) {
	print "Backup already exists at $dirname... continue anyway? [y/n]: ";
	my $input = <STDIN>;
	if ( !($input =~ "y") ) {
		exit;
	}
}

# This creates an INI file showing directory structure
open(FILE,">$dirname/backup.ini");
foreach(@databases) {
	print "Backing up database: $_\n";
	$dbh->do("USE $_;");
	print FILE "$_\n";
	my $t = $dbh->selectcol_arrayref("SHOW TABLES;");
	my @tables = @$t;
	mkdir("$dirname/$_");
	foreach my $table (@tables) {
		print "\t$table\n";
		system("mysqldump -h $dbiHost -u $dbiUsername -p$dbiPassword $_ --compact --triggers --routines --add-drop-table --tables $table > $dirname/$_/$table.sql");
		open(READ,"$dirname/$_/$table.sql");
		$/ = undef;
		my $fileContents = <READ>;
		close(READ);
		my $fileContents = $fileContents;
		open(WRITE,">$dirname/$_/$table.sql");	
		print WRITE $fileContents;
		close(WRITE);
		print FILE "\t$table\n";
	}
	print "Compressing $_... ";
	system("cd $dirname;tar -cf $_.tar $_/;gzip -f6 $_.tar;rm -rf $_/;");
	#system("cd $dirname;tar -jcvf $_.tar.bz2 $_/;rm -rf $_/;");
	print "Done.\n";
}
print "Backup written to $dirname\n";
close(FILE);

#Subroutines, NO LIVE CODE BELOW
sub dirFormat {
	my ($string) = @_;
	$string =~ s/\/$//;
	return $string;
}
